package com.jiantong.admin.controller.dongjiantong;

import com.jiantong.admin.controller.DjtBaseController;
import com.jiantong.admin.dto.CityAreaDto;
import com.jiantong.admin.dto.Fac_HarmlessDto;

import com.jiantong.admin.model.Common;
import com.jiantong.admin.model.PagingMz;
import com.jiantong.user.model.*;
import com.jiantong.user.service.*;


import com.jiantong.work.model.Harmless;


import com.jiantong.work.service.HarmlessReadService;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Paging;
import io.terminus.common.model.Response;
import org.assertj.core.util.Strings;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import java.text.DecimalFormat;


import java.util.*;

/**
 * Created by cao on 2017/7/17.
 * 无害化
 */
@Controller
@RequestMapping("/djt/harmless")

public class HarmlesslyController extends DjtBaseController {

    private static final String BaseViews = VIEWS + "harmlessly/";
    @RpcConsumer
    private UserReadService userReadService;
    @RpcConsumer
    private UserProfileReadService userProfileReadService;
    @RpcConsumer
    private BreedFactoryReadService breedFactoryReadService;
    @RpcConsumer
    private ButcherFactoryReadService butcherFactoryReadService;
    @RpcConsumer
    private HarmlessReadService harmlessReadService;
    @RpcConsumer
    private GovernmentUserDutyReadService governmentUserDutyReadService;

    //首页

    @GetMapping("dashboard")
    private String InspectorGuide(Model model, HttpServletRequest request, HttpServletResponse response) {

        Map mapuser = getarea(response, request);

        model.addAttribute("username", mapuser.get("username"));

        Common common = new Common(breedFactoryReadService, butcherFactoryReadService);
        List areaList = common.serachCityAreaDtoInBreefctory();
        List<String> typeList = harmlessReadService.reportType().getResult();
        model.addAttribute("areaList", areaList);
        model.addAttribute("typeList", typeList);
        return BaseViews + "harmstat";
    }

    @GetMapping("harmrecord")
    private String InspectorRecord() {
        return BaseViews + "harmlessyRecord";
    }

    //无害化排行
    @GetMapping("whhph")
    @ResponseBody
    private List<Map> harmlessphb(@RequestParam(required = false) Date start,
                                  @RequestParam(required = false) Date end,
                                  @RequestParam(required = false) String area,
                                  @RequestParam(required = false) Integer type
    ) {
        Map criteria = new HashMap();
        Map regionMap = new HashMap();
        List<Map> resultList = new ArrayList<>();
        List<String> regions = new ArrayList();
        if (!Strings.isNullOrEmpty(area)) {
            regions.add(area);
        } else {
            regions = breedFactoryReadService.serachAllregion("襄阳市");
        }
        for (String region : regions) {
            regionMap = ResultMap(region, start, end, type);
            resultList.add(regionMap);
        }
        Float all = 0f;
        for (Map map : resultList) {
            all += (float) map.get("areanum");
        }
        for (Map map : resultList) {
            if (!map.containsKey("zb")) {
                Float zb = (float) map.get("areanum") / all;
                map.put("zb", (float) (Math.round(zb * 10000)) / 100);
            }
        }


        return resultList;
    }

    @GetMapping("wuhaihua")
    @ResponseBody
    public List<Map> wuhaihua() {
        List<Harmless> list = harmlessReadService.pagingCommon(1, 5, new HashMap()).getResult().getData();
        Map map = new HashMap();
        List resultList = new ArrayList();
        for (Harmless harmless : list) {
            String str = "";

            BreedFactory breedFactory = breedFactoryReadService.findById(harmless.getBreedFactoryId()).getResult();
            str = breedFactory.getCity() + breedFactory.getRegion();

            map.put(str, harmless);
            resultList.add(map);
        }
        return resultList;
    }

    //无害化图
    @GetMapping("whhtu")
    @ResponseBody
    public List<Map> whhtu(@RequestParam(required = false) Date start,
                           @RequestParam(required = false) Date end,
                           @RequestParam(required = false) String area,
                           @RequestParam(required = false) Integer type) {
        Map criteria = new HashMap();
        if (start != null) {
            criteria.put("start", start);
        }
        if (end != null) {
            criteria.put("end", end);
        }
        if (type != null && type != 0) {
            criteria.put("animalType", type);
        }
        Calendar date = Calendar.getInstance();
        date.setTime(start);

        int day = differentDaysByMillisecond(start, end);
        List<Map> resutlList = new ArrayList<>();
        if (day < 8) {
            int i = 0;
            while (i < day) {
                criteria.put("start", new Date(start.getTime() + i * (1000 * 3600 * 24)));
                criteria.put("end", new Date(start.getTime() + (i + 1) * (1000 * 3600 * 24)));

                List<Map> harmList = harmlessReadService.harmlesspic(criteria).getResult();
                if (harmList != null && harmList.size() > 0) {
                    Float num = 0f;
                    for (Map map : harmList) {
                        num += (Float) map.get("quantity");
                    }
                    for (Map map : harmList) {
                        map.put("num", num);
                    }
                    Map map = ResultMapPic(area, harmList);
                    if (map == null || map.isEmpty()) {
                        Map map1 = new HashMap();
                        map1.put("空", 0);
                        map.put("空", map1);
                    }
                    resutlList.add(map);
                } else {
                    Map map = new HashMap();
                    Map map1 = new HashMap();
                    map1.put("空", 0);
                    map.put("空", map1);
                    resutlList.add(map);
                }
                i++;
            }
        } else if (day < 60) {
            int i = 0;
            while (i < day) {
                criteria.put("start", new Date(start.getTime() + i * (1000 * 3600 * 24)));
                criteria.put("end", new Date(start.getTime() + (i + 7) * (1000 * 3600 * 24)));
                List<Map> harmList = harmlessReadService.harmlesspic(criteria).getResult();
                if (harmList != null && harmList.size() > 0) {
                    Float num = 0f;
                    for (Map map : harmList) {
                        num += (Float) map.get("quantity");
                    }
                    for (Map map : harmList) {
                        map.put("num", num);
                    }
                    Map map = ResultMapPic(area, harmList);
                    if (map.isEmpty()) {
                        Map map1 = new HashMap();
                        map1.put("空", 0);
                        map.put("空", map1);
                    }
                    resutlList.add(map);
                }
                i += 7;
            }
        } else {
            int i = 0;
            while (i < day) {
                criteria.put("start", new Date(start.getTime() + i * (1000 * 3600 * 24)));
                criteria.put("end", new Date(start.getTime() + (i + 30) * (1000 * 3600 * 24)));
                List<Map> harmList = harmlessReadService.harmlesspic(criteria).getResult();
                if (harmList != null && harmList.size() > 0) {
                    Float num = 0f;
                    for (Map map : harmList) {
                        num += (Float) map.get("quantity");
                    }
                    for (Map map : harmList) {
                        map.put("num", num);
                    }
                    Map map = ResultMapPic(area, harmList);
                    if (map.isEmpty()) {
                        Map map1 = new HashMap();
                        map1.put("空", 0);
                        map.put("空", map1);
                    }
                    resutlList.add(map);
                }
                i += 30;
            }

        }
        return resutlList;
    }

    //无害化记录
    @GetMapping("harmless")
    public String harmless(Model model, HttpServletRequest request, HttpServletResponse response) {

        Map mapuser = getarea(response, request);

        model.addAttribute("username", mapuser.get("username"));

        Common common = new Common(breedFactoryReadService, butcherFactoryReadService);
        List areaList = common.serachCityAreaDtoInBreefctory();
        List<String> typeList = harmlessReadService.reportType().getResult();
        model.addAttribute("areaList", areaList);
        model.addAttribute("typeList", typeList);
        return BaseViews + "harmless";
    }

    @GetMapping("harmlessindex")
    @ResponseBody
    private PagingMz<Fac_HarmlessDto> showHarmlessIndex(@RequestParam(required = false) Integer page,
                                                        @RequestParam(required = false) Integer rows,
                                                        @RequestParam(required = false) Date start,
                                                        @RequestParam(required = false) Date end,
                                                        @RequestParam(required = false) String area,
                                                        @RequestParam(required = false) Integer type,
                                                        @RequestParam(required = false) Integer status,
                                                        @RequestParam(required = false) Integer reporttype,
                                                        @RequestParam(required = false) Integer method
    ) {
        Map criteria = new HashMap();
        if (area != null && area.length() > 0) {
            criteria.put("productName", area);
        }
        List<BreedFactory> facList = (List<BreedFactory>) breedFactoryReadService.findByArea(criteria).getResult();
        criteria.clear();
        if (start != null) {
            criteria.put("start", start);
        }
        if (end != null) {
            criteria.put("end", end);
        }
        if (type != null && type != 0) {
            criteria.put("animalType", type);
        }
        if (status != null && status != -5) {
            criteria.put("status", status);
        }
        if (reporttype != null && reporttype != 0) {
            criteria.put("reportType", reporttype);
        }
        if (method != null && method != 0) {
            criteria.put("treatment", method);
        }
        List<Fac_HarmlessDto> harmList = new ArrayList<>();
        Paging<Harmless> paging = harmlessReadService.pagingCommon(page, rows, criteria).getResult();
        if (paging == null) {
            return new PagingMz<>();
        }
        for (BreedFactory factory : facList) {
            for (Harmless harm : paging.getData()) {
                if (factory.getId().equals(harm.getBreedFactoryId())) {
                    harmList.add(new Fac_HarmlessDto(factory, harm));
                }
            }
        }
        Integer size = 0;
        if(harmList!=null && harmList.size()>0){
            size = harmList.size();
        }

        Long records = Long.parseLong(size.toString());
        Long pagetotal = (records - 1) / rows + 1;
        return new PagingMz<>(pagetotal, records, page, harmList);
    }


    @GetMapping("harmlessDetail")
    public String derict() {
        return BaseViews + "harmlessDetail";
    }


    private Boolean ResutlCompare(Result result1, Result result2) {
        if (result1.getRegion().equals(result2.getRegion())) {
            if (result1.getType() == result2.getType()) {
                return true;
            }
        }
        return false;
    }

    private Map ResultMap(String region, Date start, Date end, Integer type) {
        Calendar c = Calendar.getInstance();
        Map criteria = new HashMap();
        List<BreedFactory> breedList = new ArrayList<>();
        Map resultMap = new HashMap();
        criteria.put("region", region);
        breedList = (List<BreedFactory>) breedFactoryReadService.findByArea(criteria).getResult();
        if (breedList == null && breedList.size() == 0) {
            Map map1 = new HashMap();
            map1.put("area", region);
            switch (type) {
                case 1:
                    map1.put("type", "猪");
                    break;
                case 2:
                    map1.put("type", "牛");
                    break;
                case 3:
                    map1.put("type", "羊");
                    break;
                case 4:
                    map1.put("type", "家禽");
                    break;
                default:
                    map1.put("type", "全部");
                    break;
            }
            map1.put("areanum", 0f);
            map1.put("tb", 0f);
            map1.put("hb", 0f);
            map1.put("zb", 0f);

            return map1;
        } else {
            criteria.clear();
            float qu = 0f;
            float tb = 0f;
            float hb = 0f;
            float num = 0f;
            List<Long> ids = new ArrayList<>();
            for (BreedFactory breedFactory : breedList) {
                ids.add(breedFactory.getId());
            }
                criteria.clear();
                criteria.put("breedFactoryIds", ids);
                if (start != null) {
                    criteria.put("start", start);
                }
                if (end != null) {
                    criteria.put("end", end);
                }
                if (type != null && type != 0) {
                    criteria.put("animalType", type);
                }

                List<Harmless> list = harmlessReadService.selectByFactoryIds(criteria).getResult();
                if (list != null && list.size() > 0) {
                    for (Harmless harmless : list) {
                        num += harmless.getQuantity();
                    }
                }

                resultMap.put("area", region);
            switch (type) {
                case 1:
                    resultMap.put("type", "猪");
                    break;
                case 2:
                    resultMap.put("type", "牛");
                    break;
                case 3:
                    resultMap.put("type", "羊");
                    break;
                case 4:
                    resultMap.put("type", "家禽");
                    break;
                default:
                    resultMap.put("type", "全部");
                    break;
            }
            qu = num;
            resultMap.put("areanum", num);
            ///////////////
            c.setTime(start);
            c.add(Calendar.YEAR, -1);
            criteria.put("start", c.getTime());
            c.setTime(end);
            c.add(Calendar.YEAR, -1);
            criteria.put("end", c.getTime());
            num = 0f;
            ids.clear();
            for (BreedFactory breedFactory : breedList) {
                ids.add(breedFactory.getId());
            }
                criteria.clear();
                criteria.put("breedFactoryIds", ids);
                if (start != null) {
                    criteria.put("start", start);
                }
                if (end != null) {
                    criteria.put("end", end);
                }
                if (type != null && type != 0) {
                    criteria.put("animalType", type);
                }
                List<Harmless> list1 = harmlessReadService.selectByFactoryIds(criteria).getResult();
                if (list1 != null && list1.size() > 0) {
                    for (Harmless harmless : list1) {
                        num += harmless.getQuantity();
                    }
                }
            tb = (qu - num) / num;
            resultMap.put("tb", (float) (Math.round(tb * 10000)) / 100);
            ////////////
            Long a = end.getTime() - start.getTime();
            criteria.put("start", new Date(start.getTime() - a));
            criteria.put("end", start);
            num = 0f;
            ids.clear();
            for (BreedFactory breedFactory : breedList) {
                ids.add(breedFactory.getId());
            }
                criteria.clear();
                criteria.put("breedFactoryIds", ids);
                if (start != null) {
                    criteria.put("start", start);
                }
                if (end != null) {
                    criteria.put("end", end);
                }
                if (type != null && type != 0) {
                    criteria.put("animalType", type);
                }
                List<Harmless> list2 = harmlessReadService.selectByFactoryIds( criteria).getResult();
                if (list2 != null && list2.size() > 0) {
                    for (Harmless harmless : list2) {
                        num += harmless.getQuantity();
                    }
                }
            hb = (qu - num) / num;
            resultMap.put("hb", (float) (Math.round(hb * 10000)) / 100);
        }
        return resultMap;
    }


    private Map ResultMapPic(String area, List<Map> harmList) {
        Map mapresult = new HashMap();
        Iterator harmIterator = harmList.iterator();
        while (harmIterator.hasNext()) {
            Map map = (Map) harmIterator.next();
            if (map == null) {
                return new HashMap();
            }

            BreedFactory breedFactory = breedFactoryReadService.findById((Long) map.get("breed_factory_id")).getResult();
            if (area != null && area.length() > 0 && breedFactory != null && !area.equals(breedFactory.getRegion())) {
                harmIterator.remove();
            } else {
                if (breedFactory != null) {
                    if (breedFactory != null && mapresult.containsKey(breedFactory.getRegion())) {
                        Map map2 = (Map) mapresult.get(breedFactory.getRegion());
                        if (map2 != null && map2.containsKey(map.get("treatment"))) {
                            map2.put(map.get("treatment"), (Float) map2.get(map.get("treatment")) + (map == null ? 0f : (Float) map.get("quantity")));
                        } else {
                            map2.put(map.get("treatment"), map.get("quantity"));
                        }
                    } else {
                        Map map1 = new HashMap();
                        map1.put(map.get("treatment"), map.get("quantity"));
                        mapresult.put(breedFactory.getRegion(), map1);
                    }
                }
            }
        }
        return mapresult;
    }

    private int differentDaysByMillisecond(Date date1, Date date2) {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
        return days;
    }


    public Map getarea(HttpServletResponse response, HttpServletRequest request) {
        List<String> list = new ArrayList<>();
        list.add("province");
        list.add("city");
        list.add("region");
        list.add("street");
        list.add("village");
        Cookie[] cookies = null;
        cookies = request.getCookies();
        String name = "";
        Map map = new HashMap();
        for (Cookie cookie : cookies) {

            if (cookie.getName().equals("djtid")) {
                String id = cookie.getValue();
                int Id = Integer.parseInt(id);
                Response<User> userResponse = userReadService.findById(Integer.toUnsignedLong(Id));
                name = userResponse.getResult().getName();
                map.put("username", name);
                switch (userResponse.getResult().getAreaLevel()) {
                    case 1:
                        UserProfile userProfile = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String Province = userProfile.getProvince();
                        Map map6 = new HashMap();
                        map6.put("province", Province);
                        List<BreedFactory> breedFactoryList = (List<BreedFactory>) breedFactoryReadService.findByArea(map6).getResult();
                        //获取所有省下城市

                        Map map1 = new HashMap();
                        map1.put("area1", list.get(1));
                        map1.put("area2", list.get(0));
                        map1.put("area3", Province);
                        List<String> citys = breedFactoryReadService.serachAllregion1(map1);
                        //获取城市下所有区
                        List<CityAreaDto> cityAreaDtoList = new ArrayList<>();
                        for (String city : citys) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map map2 = new HashMap();
                            map2.put("area1", list.get(2));
                            map2.put("area2", list.get(1));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList.add(cityAreaDto);

                        }
                        map.put("cityAreaDtoList", cityAreaDtoList);
                        map.put("breedFactorys", breedFactoryList);
                        //switch break;
                        break;
                    case 2:
                        UserProfile userProfile2 = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String city1 = userProfile2.getCity();
                        Map map7 = new HashMap();
                        map7.put("city", city1);
                        List<BreedFactory> breedFactoryList1 = (List<BreedFactory>) breedFactoryReadService.findByArea(map7).getResult();
                        //获取所有省下城市

                        Map map21 = new HashMap();
                        map21.put("area1", list.get(2));
                        map21.put("area2", list.get(1));
                        map21.put("area3", city1);
                        List<String> citys2 = breedFactoryReadService.serachAllregion1(map21);
                        //获取城市下所有区
                        List<CityAreaDto> cityAreaDtoList1 = new ArrayList<>();
                        for (String city : citys2) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map map2 = new HashMap();
                            map2.put("area1", list.get(3));
                            map2.put("area2", list.get(2));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList1.add(cityAreaDto);

                        }
                        map.put("cityAreaDtoList", cityAreaDtoList1);
                        map.put("breedFactorys", breedFactoryList1);
                        //switch break;
                        break;
                    case 3://区
                        UserProfile userProfile3 = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String region = userProfile3.getRegion();
                        Map map36 = new HashMap();
                        map36.put("region", region);
                        List<BreedFactory> breedFactoryList3 = (List<BreedFactory>) breedFactoryReadService.findByArea(map36).getResult();
                        //获取所有区下城市镇

                        Map map31 = new HashMap();
                        map31.put("area1", list.get(3));
                        map31.put("area2", list.get(2));
                        map31.put("area3", region);
                        List<String> citys3 = breedFactoryReadService.serachAllregion1(map31);
                        //获取对应镇 对应村
                        List<CityAreaDto> cityAreaDtoList3 = new ArrayList<>();
                        for (String city : citys3) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map map2 = new HashMap();
                            map2.put("area1", list.get(4));
                            map2.put("area2", list.get(3));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList3.add(cityAreaDto);

                        }
                        map.put("cityAreaDtoList", cityAreaDtoList3);
                        map.put("breedFactorys", breedFactoryList3);
                        //switch break;
                        break;
                    case 4://镇
                        UserProfile userProfile4 = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String street = userProfile4.getStreet();
                        Map map46 = new HashMap();
                        map46.put("street", street);
                        List<BreedFactory> breedFactoryList4 = (List<BreedFactory>) breedFactoryReadService.findByArea(map46).getResult();
                        //获取所有镇下所有村

                        Map map41 = new HashMap();
                        map41.put("area1", list.get(4));
                        map41.put("area2", list.get(3));
                        map41.put("area3", street);
                        List<String> citys4 = breedFactoryReadService.serachAllregion1(map41);//所有村

                        List<CityAreaDto> cityAreaDtoList4 = new ArrayList<>();

                        CityAreaDto cityAreaDto = new CityAreaDto();

                        cityAreaDto.setCity(street);
                        cityAreaDto.setRegions(citys4);
                        cityAreaDtoList4.add(cityAreaDto);


                        map.put("cityAreaDtoList", cityAreaDtoList4);
                        map.put("breedFactorys", breedFactoryList4);
                        //switch break;
                        break;
                    case 5://村
                        List<GovernmentUserDuty> governmentUserDutyList = governmentUserDutyReadService.findGovernmentUserDutiesByUserId(userResponse.getResult().getId(), null).getResult();
                        List<Long> longlist = new ArrayList<>();
                        for (GovernmentUserDuty governmentUserDuty : governmentUserDutyList) {
                            longlist.add(governmentUserDuty.getFactoryOrPointId());
                        }
                        List<String> villages = new ArrayList<>();
                        List<BreedFactory> breedFactoryList2 = breedFactoryReadService.findBreedFactoryDtoByIds(longlist).getResult();
                        for (BreedFactory breedFactory : breedFactoryList2) {
                            villages.add(breedFactory.getVillage());
                            ;
                        }

                        List<String> listWithoutDup = new ArrayList<String>(new HashSet<String>(villages));


                        List<CityAreaDto> cityAreaDtoList5 = new ArrayList<>();

                        CityAreaDto cityAreaDto1 = new CityAreaDto();
                        cityAreaDto1.setCity(" ");

                        // cityAreaDto1.setCity(village);
                        cityAreaDto1.setRegions(listWithoutDup);

                        cityAreaDtoList5.add(cityAreaDto1);


                        map.put("cityAreaDtoList", cityAreaDtoList5);
                        map.put("breedFactorys", breedFactoryList2);
                        //switch break;
                        break;
                }


                break;
            }

        }

        return map;
    }


    public List findFactoryIdByArea(String region, int breedType) {

        Map map = new HashMap();
        if (breedType == -1) {
            map.put("breedType", null);
        } else {
            map.put("breedType", breedType);
        }
        List<String> list1 = new ArrayList<>();
        String[] list = region.split(",");

        for (int i = 0; i < list.length; i++) {
            list1.add(list[i]);
        }
        map.put("areas", list1);

        List<BreedFactory> breedFactoryList = (List<BreedFactory>) breedFactoryReadService.findByArea(map).getResult();

        return breedFactoryList;
    }


}


class Result {
    private String region;
    private Integer type;

    public String getRegion() {
        return region;
    }

    public Integer getType() {
        return type;
    }

    public void setRegion(String region) {
        this.region = region;
    }

    public void setType(Integer type) {
        this.type = type;
    }

    public Result() {
        region = "";
        type = 0;
    }

}